import React, { useEffect, useCallback, useState } from 'react'
import { getSysMarkFindMark } from '../../../../../../Api/communalUrl'
import { sysUploadUrl } from '../../../../../../Api/fileUrl'
import { putLsCarWhiteInsertLsCarWhite, getLsCarWhiteEcho, postLsCarWhiteUpdateLsCarWhite } from '../../../../api'
import { Modal, Form, Input, TimePicker, message, Radio, Select, DatePicker, Upload } from 'antd'
import moment from 'moment'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';

const { Option } = Select;

/**
 * @description: 添加、修改白名单页面
 * @author: xiaoxujs
 * @updata: xiaoxujs（2021-08-16） 修改添加类型
 */

const AddWhiteListModule = ({
    addWhiteListModuleShow,
    setAddWhiteListModuleShow,
    listFun,
    clickId,
    setClickId
}) => {
    const [form] = Form.useForm()
    const { validateFields, resetFields, setFieldsValue } = form
    const [moreItem, setMoreItem] = useState(false)
    const [vehicleType, setVehicleType] = useState([]); //车辆类型
    const [licenseColor, setLicenseColor] = useState([]) // 车牌颜色
    const [useCharacter, setUseCharacter] = useState([]); // 使用性质
    const [standardType, setStandardType] = useState([]); //排放阶段
    const [imageUrl, setImageUrl] = useState(undefined)
    const [loading, setLoading] = useState(false)
    const typeFun = useCallback(
        () => {
            /**
             * 产品类型: PRODUCT-TYPE 
                客户来源: RESOURCE 
                车辆类型: VEHICLE-TYPE 
                车牌颜色: LICENSE-COLOR 
                使用性质: USE-CHARACTER 
                排放阶段: STANDARD
             */
                //车辆类型
                ; (async () => {
                    const { code, msg, data } = await getSysMarkFindMark({ typeCode: 'VEHICLE-TYPE' })
                    if (code === '20000') {
                        setVehicleType(data)
                    } else {
                        message.error(msg)
                    }
                })()
                //车牌颜色
                ; (async () => {
                    const { code, msg, data } = await getSysMarkFindMark({ typeCode: 'LICENSE-COLOR' })
                    if (code === '20000') {
                        setLicenseColor(data)
                    } else {
                        message.error(msg)
                    }
                })()
                // 使用性质
                ; (async () => {
                    const { code, msg, data } = await getSysMarkFindMark({ typeCode: 'USE-CHARACTER' })
                    if (code === '20000') {
                        setUseCharacter(data)
                    } else {
                        message.error(msg)
                    }
                })()
                // 排放阶段
                ; (async () => {
                    const { code, msg, data } = await getSysMarkFindMark({ typeCode: 'STANDARD' })
                    if (code === '20000') {
                        setStandardType(data)
                    } else {
                        message.error(msg)
                    }
                })()
        },
        [],
    )
    const detailsFun = useCallback(
        () => {
            if (clickId) {
                ; (async () => {
                    const { code, msg, data } = await getLsCarWhiteEcho({ id: clickId })
                    if (code === '20000') {
                        setMoreItem(true)
                        data.time = [
                            moment(data.startDate, 'HH:mm:ss'),
                            moment(data.endDate, 'HH:mm:ss')
                        ]
                        if (data.issueDate) {
                            data.issueDate = moment(data.issueDate, 'YYYY-MM-DD')
                        }
                        if (data.registerDate) {
                            data.registerDate = moment(data.registerDate, 'YYYY-MM-DD')
                        }
                        setImageUrl(data.drivingLicenseImg)
                        data.drivingLicenseImg = [{
                            uid: data.drivingLicenseImg,
                            name: data.drivingLicenseImg,
                            status: 'done',
                            url: data.drivingLicenseImg,
                        },]


                        data.catType = true
                        setFieldsValue(data)
                    } else {
                        message.error(msg)
                    }
                })()
            }
        },
        [clickId, setFieldsValue],
    )
    useEffect(() => {
        detailsFun()
        typeFun()
    }, [detailsFun, typeFun])
    const beforeUpload = (file) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    }
    const handleChange = info => {
        if (info.file.status === 'uploading') {
            setLoading(true)
            return;
        }
        if (info.file.status === 'done') {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj, imageUrl => {
                setLoading(false)
                setImageUrl(imageUrl)
            }

            );
        }
    };
    const getBase64 = (img, callback) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    }

    const handleOk = () => {
        validateFields().then(values => {
            values.startDate = moment(values.time[0]).format('HH:mm:ss')
            values.endDate = moment(values.time[1]).format('HH:mm:ss')
            delete values.time
            if (values.catType) {
                values.registerDate = moment(values.registerDate).format('YYYY-MM-DD')
                values.issueDate = moment(values.issueDate).format('YYYY-MM-DD')
                if(values.drivingLicenseImg[values.drivingLicenseImg.length -1].url) {
                    values.drivingLicenseImg = values.drivingLicenseImg[values.drivingLicenseImg.length -1].url
                }else{
                        values.drivingLicenseImg = values.drivingLicenseImg[values.drivingLicenseImg.length -1].response.data
                }
                
            }
            delete values.catType
            if (clickId) {
                values.id = clickId
                    ; (async () => {
                        const { code, msg } = await postLsCarWhiteUpdateLsCarWhite(values)
                        if (code === '20000') {
                            message.success('编辑成功！')
                            resetFields()
                            listFun()
                            setClickId(undefined)
                            setAddWhiteListModuleShow(false)
                        } else {
                            message.error(msg)
                        }
                    })()
            } else {
                ; (async () => {
                    const { code, msg } = await putLsCarWhiteInsertLsCarWhite(values)
                    if (code === '20000') {
                        message.success('添加成功！')
                        resetFields()
                        listFun()
                        setClickId(undefined)
                        setAddWhiteListModuleShow(false)
                    } else {
                        message.error(msg)
                    }
                })()
            }

        })
    };

    const handleCancel = () => {
        resetFields()
        setClickId(undefined)
        setAddWhiteListModuleShow(false);
    };
    const handleChangeCatType = e => {
        setMoreItem(e.target.value)
    }
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );
    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    };
    return <Modal
        title={clickId ? '编辑白名单' : '添加白名单'}
        visible={addWhiteListModuleShow}
        onOk={handleOk}
        onCancel={handleCancel}
    >
        <Form
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            form={form}
        >
            <Form.Item
                label="车主姓名"
                name="carMaster"
                rules={[{ required: true, message: '请输入车主姓名!' }]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="车牌号"
                name="carNo"
                rules={[
                    { required: true, message: '请输入车牌号!' },
                    {
                        pattern: /(^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$)/, message: '请输入正确车牌号'
                    }]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="车主电话"
                name="mobile"
                rules={[
                    { required: true, message: '请输入车主电话!' },
                    {
                        pattern: /^1[3-9]\d{9}$/,
                        message: '请输入正确的手机号！'
                    }
                ]}
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="有效时间"
                name="time"
                rules={[{ required: true, message: '请选择有效时间!' }]}
            >
                <TimePicker.RangePicker />
            </Form.Item>
            <Form.Item
                label="车辆类型"
                name="catType"
                rules={[{ required: true, message: '请选择车辆类型!' }]}
            >
                <Radio.Group onChange={handleChangeCatType}>
                    <Radio value={false}>普通车辆</Radio>
                    <Radio value={true}>3.5 吨及以上柴油车</Radio>
                </Radio.Group>
            </Form.Item>
            {
                moreItem ? <>
                    <Form.Item
                        label="号牌颜色"
                        name="licenseColor"
                        rules={[{ required: true, message: '请选择号牌颜色' }]}
                    >
                        <Select style={{ width: 120 }} >
                            {
                                licenseColor.map(item => <Option value={item.markValue} key={item.markValue}>{item.markName}</Option>)
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="车辆类型"
                        name="vehicleType"
                        rules={[{ required: true, message: '请选择车辆类型' }]}
                    >
                        <Select style={{ width: 240 }} >
                            {
                                vehicleType.map(item => <Option value={item.markValue} key={item.markValue}>{item.markName}</Option>)
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="使用性质"
                        name="useCharacter"
                        rules={[{ required: true, message: '请选择使用性质' }]}
                    >
                        <Select style={{ width: 240 }} >
                            {
                                useCharacter.map(item => <Option value={item.markValue} key={item.markValue}>{item.markName}</Option>)
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="发动机号码"
                        name="engineNo"
                        rules={[{ required: true, message: '请发动机号码' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="车架号VIN"
                        name="vin"
                        rules={[
                            { len: 17, message: '车架号应该为17位' },
                            { required: true, message: '请输入车架号' }
                        ]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="住址"
                        name="address"
                        rules={[{ required: true, message: '请填写住址' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="品牌型号"
                        name="model"
                        rules={[{ required: true, message: '请输入品牌型号' }]}
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        label="注册日期"
                        name="registerDate"
                        rules={[{ required: true, message: '请选择注册日期' }]}
                    >
                        <DatePicker />
                    </Form.Item>
                    <Form.Item
                        label="发证日期"
                        name="issueDate"
                        rules={[{ required: true, message: '请选择发证日期' }]}
                    >
                        <DatePicker />
                    </Form.Item>
                    <Form.Item
                        label="排放阶段"
                        name="emissionStandard"
                        rules={[{ required: true, message: '请选择排放阶段' }]}
                    >

                        <Select style={{ width: 240 }} >
                            {
                                standardType.map(item => <Option value={item.markValue} key={item.markValue}>{item.markName}</Option>)
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        label="行驶证照片"
                        name="drivingLicenseImg"
                        valuePropName="fileList" 
                        getValueFromEvent={normFile}
                        rules={[{ required: true, message: '请上传驾驶证' }]}
                    >
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action={sysUploadUrl()}
                            beforeUpload={beforeUpload}
                            headers={{
                                authentication: sessionStorage.getItem("token")
                            }}
                            data={{ folder: '/license' }}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        label="燃料类型"
                        name="fuelType"
                        rules={[{ required: true, message: '请输入燃料类型' }]}
                    >
                        <Input />
                    </Form.Item>
                </> : null
            }
        </Form>
    </Modal>
}

export default AddWhiteListModule